import { Spin } from 'antd';
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation, useParams } from 'react-router-dom';

import { FilterArea, ProductList } from '../../components';
import { MainLayout } from '../../layouts/main-layout';
import { useSelector } from '../../redux/hooks';
import { getProductSearch } from '../../redux/product-search/slice';
import styles from './search-page.module.css';

interface MatchParams {
  keywords: string;
}
export const SearchPage: React.FC = () => {
  const { keywords } = useParams<MatchParams>();

  const loading = useSelector((state) => state.productSearch.loading);
  const error = useSelector((state) => state.productSearch.error);
  const pagination = useSelector((state) => state.productSearch.pagination);
  const productList = useSelector((state) => state.productSearch.data);

  const location = useLocation();
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getProductSearch({ keywords, nextPage: 1, pageSize: 10 }) as any);
  }, [location]);

  const onPageChange = (nextPage, pageSize) => {
    dispatch(getProductSearch({ nextPage, pageSize, keywords }) as any);
  };
  if (loading) {
    return (
      <Spin
        size="large"
        style={{
          marginTop: 200,
          marginBottom: 200,
          marginLeft: 'auto',
          marginRight: 'auto',
          width: '100%'
        }}
      />
    );
  }
  if (error) {
    return <div>网站出错：{error}</div>;
  }
  return (
    <>
      <MainLayout>
        {/* 分类过滤器 */}
        <div className={styles['product-list-container']}>
          <FilterArea />
        </div>
        {/* 产品列表 */}
        <div className={styles['product-list-container']}>
          <ProductList data={productList} paging={pagination} onPageChange={onPageChange} />
        </div>
      </MainLayout>
    </>
  );
};
